package name.luoyong.spring.sample.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import name.luoyong.spring.sample.entity.User;

@Repository
public class UserDao {

	@PersistenceContext
	private EntityManager em;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	public UserDao() {
		System.out.println("****** UserDao init ******");
	}

	public void save(User user) {
		em.persist(user);
	}

	public User get(Long id) {
		return em.find(User.class, id);
	}
	
	public void update(User user) {
		em.merge(user);
	}

	public void delete(User user) {
		em.remove(user);
	}

	public int delete(Long id) {
		return em.createQuery("delete from User where id=:id").setParameter("id", id).executeUpdate();
	}

	public User getUserByUsername(String username) {
		return (User) em.createQuery("from User where username=:username").setParameter("username", username).getSingleResult();
	}

	public List<User> getAllUsers() {
		return em.createQuery("from User").getResultList();
	}

	public int countByUsername(String username) {
		return jdbcTemplate.queryForObject(
				"select count(id) from users where username=?", new Object[] { username }, Integer.class);
	}

}
